<template>
  <div>
    <page-header :title="$t('product.title')">
      <n-button
        v-auth="ProductPermEnum.CREATE"
        type="primary"
        @click.stop="handleClickAdd"
      >
        新增
      </n-button>
    </page-header>
    <div class="mt-[16px]">
      <n-grid x-gap="12" :cols="4">
        <n-gi>
          <n-select
            clearable
            value-field="id"
            label-field="name"
            :options="categoriesList"
            v-model:value="paginationResult.categoryId"
            placeholder="请选择产品类别"
            @update:value="handleSearch"
          />
        </n-gi>
        <n-gi>
          <n-select
            clearable
            value-field="id"
            label-field="name"
            :options="brandsList"
            v-model:value="paginationResult.brandId"
            placeholder="请选择品牌"
            @update:value="handleSearch"
          />
        </n-gi>
      </n-grid>
      <div class="mt-[16px]"></div>
      <BasicTable
        :table-props="tableResult"
        :columns="columns"
        :pagination-props="paginationResult"
        maxHeight="66vh"
        minHeight="48vh"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { NButton, NIcon, NSwitch } from "naive-ui";
import { Trash, CreateOutline } from "@vicons/ionicons5";
import { debounce, get } from "lodash-es";
import { ref, onMounted, h } from "vue";
import { useRouter } from "vue-router";
import { useTableHook } from "@/components/normal/basicTable/useTableHook";
import { getProducts, searchEs } from "@/api/product/product.api";
import { getBrands } from "@/api/product/brand.api";
import { getCategories } from "@/api/product/category.api";
import { Category } from "@/types/model/product/vos/category.vo";
import {
  PRODUCT_ADD_PAGE,
  PRODUCT_DETAIL_PAGE,
} from "@/router/routerNames/index";
import { ProductPermEnum } from "@/enums/permission/index";

const columns = [
  {
    title: "#",
    type: "index",
    key: "key",
    render: (_: any, index: number) => {
      return `${index + 1}`;
    },
  },
  {
    title: "产品名称",
    key: "name",
  },
  {
    title: "类别",
    key: "categoryName",
  },
  {
    title: "品牌",
    key: "brandName",
  },
  {
    title: "排序",
    key: "sort",
  },
  {
    title: "最后更新时间",
    key: "updateTime",
  },
  {
    title: "状态",
    key: "status",
    render: (row: any) => {
      return [
        h(NSwitch, {
          checkedValue: "1",
          uncheckedValue: "0",
          value: row.status,
          onUpdateValue(v) {
            row.status = v;
          },
        }),
      ];
    },
  },
  {
    title: "操作",
    key: "actions",
    align: "right",
    render: (_: any) => {
      return [
        h(
          NButton,
          {
            size: "small",
            type: "primary",
            secondary: true,
            class: "mr-2",
            onClick: () => {
              router.push({
                name: PRODUCT_DETAIL_PAGE.NAME,
                params: {
                  id: _.id,
                },
              });
            },
          },
          {
            icon: () =>
              h(NIcon, null, {
                default: () => h(CreateOutline),
              }),
          }
        ),
        h(
          NButton,
          {
            size: "small",
            type: "error",
            secondary: true,
          },
          {
            icon: () =>
              h(NIcon, null, {
                default: () => h(Trash),
              }),
          }
        ),
      ];
    },
  },
];

const router = useRouter();

const { tableResult, paginationResult, getDataList } = useTableHook<any>({
  api: getProducts,
  queryForm: {
    categoryId: undefined,
    brandId: undefined,
  },
});

const categoriesList = ref<Category[]>([]);
const brandsList = ref<any[]>([]);

const handleClickAdd = () => {
  router.push({
    name: PRODUCT_ADD_PAGE.NAME,
  });
};

const getBrandsList = async () => {
  try {
    const result = await getBrands({
      page: 1,
      pageSize: 1000,
    });
    brandsList.value = get(result, "result.records") || [];
  } catch (err) {
    console.log(err);
  }
};

const getCategoriesList = async () => {
  try {
    const result = await getCategories({
      page: 1,
      pageSize: 1000,
    });
    categoriesList.value = get(result, "result.records") || [];
  } catch (err) {
    console.log(err);
  }
};

const handleSearch = debounce(function () {
  paginationResult.page = 1;
  getDataList();
}, 200);

const init = () => {
  getCategoriesList();
  getBrandsList();
  getDataList();
};

onMounted(() => {
  init();
  searchEs({
    keyword: "测",
  });
});
</script>
